<template>
  <div>
    <set-time ref="setTime" :startProduce="startProduce"></set-time>
    <work-line ref="workLine" @refreshWorkLine="refreshWorkLine" :workList="workList"
               :startProduce="startProduce"></work-line>
    <div style="margin-left: 15%;margin-top: 7%">
      <el-button type="primary" style="margin-left: 22%;" @click="startProducing" v-show="!startProduce">开始生产
      </el-button>
      <el-button type="primary" class="noEditProduce" style="margin-left: 22%;" v-show="startProduce">开始生产</el-button>
      <el-button type="warning" style="margin-left: 22%" @click="lockProduce">锁定生产</el-button>
    </div>
  </div>
</template>
<script>
  import setTime from './setTime';
  import workLine from './workLine';
  import {getToken} from '@/utils/auth' // 验权
  export default {
    nameL: 'workSpace',
    data() {
      return {
        startProduce: false,
        workId: '',
        lockStatus: '0',
        workLineType: '',
        notEmptyAttr: ["editStartTime", "editUpTime", "editMiddleTime", "editDownTime", "editEndTime"],
        originMap: {
          editStartTime: "startTime",
          editUpTime: "upTime",
          editMiddleTime: "middleTime",
          editDownTime: "downTime",
          editEndTime: "endTime"
        },
        workList: [],
        workLineAttr: ["targetOutput", "planUserCount", "actualUserCount", "muPlan", "targetEfficiency"]
      }
    },
    mounted() {
      let self = this;
      let work = self.$store.state.userInfo.works;
      let user = JSON.parse(getToken());
      self.workId = work.workId;
      self.workLineType = user.userDetail.workId;
      self.getWorkLineStartStatus();
    },
    components: {
      setTime,
      workLine
    },
    methods: {
      startProducing() {
        if (!this.startProduce) {
          let time = this.$refs.setTime.getApiTableData();
          let workLine = this.$refs.workLine.getApiTableData();
          let flag = this.isEmpty(time);
          flag = this.inScope(time);
          flag = this.validatorStartAndEndTime(time);
          flag = this.isNumber(workLine);
          if (flag) {
            this.updateLineStatus(workLine);
          }
        }
      },

      lockProduce() {
        let self = this;
        let workLine = this.$refs.workLine.getApiTableData();
        let flag = this.isNumber(workLine);
        if(flag){
          return false;
        }
        if(self.lockStatus != '0'){
          this.$notify({
            title: '提示',
            message: "已经锁定生产线！",
            type: 'warning'
          });
          return false;
        }
        self.$confirm('确定锁定生产线？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = [];
          for (let data of workLine) {
            let _p = {id: data.id.value};
            param.push(_p);
          }
          self.$http({
            url: "/autoMonitor/workLine/updateLineLock",
            method: "post",
            data: JSON.stringify(param),
            dataType: 'json',
            contentType: "application/json",
          }).then(resp => {
            if (resp.success) {
              self.lockStatus = "1";
              self.$notify({
                title: '提示',
                message: "锁定成功！",
                type: 'warning'
              });
            }
          });
        })
      },

      updateLineStatus(workLine) {
        let self = this;
        let param = [];
        for (let data of workLine) {
          let _p = {id: data.id.value};
          param.push(_p);
        }
        self.$http({
          url: "/autoMonitor/workLine/updateLineStatus",
          method: "post",
          data: JSON.stringify(param),
          dataType: 'json',
          contentType: "application/json",
        }).then(resp => {
          if (resp.success) {
            self.startProduce = true;
            self.$notify({
              title: '提示',
              message: "开始生产！",
              type: 'warning'
            });
          }
        });
      },

      isNumber(workLine) {
        for (let line of workLine) {
          for (let attr of this.workLineAttr) {
            let data = line[attr];
            if (!data.value || !(/^[0-9]+.?[0-9]*$/.test(data.value)) || data.value == 0) {
              this.$notify({
                title: '提示',
                message: "请输入数字！",
                type: 'error'
              });
              return false;
            }
          }
        }
        return true;
      },

      updateTime(time) {
        let self = this;
        let param = {
          workId: time.workId.displayValue,
          editStartTime: time.editStartTime.displayValue,
          editUpTime: time.editUpTime.displayValue, editMiddleTime: time.editMiddleTime.displayValue,
          editDownTime: time.editDownTime.displayValue, editEndTime: time.editEndTime.displayValue
        };
        self.$http({
          url: "/autoMonitor/work/updateWorkTime",
          method: "post",
          params: param
        }).then(resp => {
          if (resp.success) {
            self.startProduce = true;
          }
        });
      },

      insertWorkLine(workLine) {
        let self = this;
        let param = [];
        for (let work of workLine) {
          let _p = {
            workId: self.workId,
            actualUserCount: work.actualUserCount.value,
            muPlan: work.muPlan.value,
            planUserCount: work.planUserCount.value,
            targetEfficiency: work.targetEfficiency.value,
            targetOutput: work.targetOutput.value,
            workLineId: work.workLineId.value
          };
          param.push(_p);
        }
        self.$http({
          url: "/autoMonitor/workLine/addLineDetail",
          method: "post",
          data: JSON.stringify(param),
          dataType: 'json',
          contentType: "application/json",
        }).then(resp => {

        });
      },

      validatorStartAndEndTime(time) {
        let startTime = time["editStartTime"];
        if (startTime && startTime.displayValue) {
          let AStartTimeSplit = startTime.displayValue.split(":");
          let AStartTime = parseInt(AStartTimeSplit[0]) * 3600 + parseInt(AStartTimeSplit[1]) * 60 + parseInt(AStartTimeSplit[2]);
          let now = new Date();
          let nowTime = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
          if (AStartTime <= nowTime) {
            this.$notify({
              title: '提示',
              message: "开始时间大于当前时间！",
              type: 'error'
            });
            return false
          }
          return true;
        }
      },

      inScope(time) {
        for (let attr of this.notEmptyAttr) {
          let data = time[attr].displayValue;
          let originData = time[this.originMap[attr]].displayValue;
          let splitData = data.split("-");
          let splitOriginData = originData.split("-");
          if (splitData.length > 1 && splitOriginData.length > 1) {
            let startData = splitData[0];
            let endData = splitData[1];
            let originStartData = splitOriginData[0];
            let originEndData = splitOriginData[1];
            let flag = this.getTimeSecond(startData, endData, originStartData, originEndData);
            if (!flag) {
              this.$notify({
                title: '提示',
                message: "休息的时间不能超过设置的范围！",
                type: 'error'
              });
              return false
            }
          }
        }
        return true;
      },

      getTimeSecond(startData, endData, startOriginData, endOriginData) {
        let AStartTimeSplit = startData.split(":");
        let AEndTimeSplit = endData.split(":");
        let BStartTimeSplit = startOriginData.split(":");
        let BEndTimeSplit = endOriginData.split(":");
        let AStartTime = parseInt(AStartTimeSplit[0]) * 3600 + parseInt(AStartTimeSplit[1]) * 60 + parseInt(AStartTimeSplit[2]);
        let AEndTime = parseInt(AEndTimeSplit[0]) * 3600 + parseInt(AEndTimeSplit[1]) * 60 + parseInt(AEndTimeSplit[2]);
        let BStartTime = parseInt(BStartTimeSplit[0]) * 3600 + parseInt(BStartTimeSplit[1]) * 60 + parseInt(BStartTimeSplit[2]);
        let BndTime = parseInt(BEndTimeSplit[0]) * 3600 + parseInt(BEndTimeSplit[1]) * 60 + parseInt(BEndTimeSplit[2]);
        return (AStartTime >= BStartTime && AEndTime <= BndTime)
      },


      isEmpty(time) {
        for (let attr of this.notEmptyAttr) {
          let data = time[attr];
          if (!data.displayValue) {
            this.$notify({
              title: '提示',
              message: "时间不能为空！",
              type: 'error'
            });
            return false;
          }
        }
        return true;
      },

      refreshWorkLine() {
        this.getWorkLineStartStatus();
      },

      getWorkLineStartStatus() {
        let self = this;
        self.$http({
          url: "/autoMonitor/workLine/queryWorkByWorkId",
          method: "post",
          params: {workId: self.workId, workLineType: self.workLineType}
        }).then(resp => {
          if (resp.success) {
            if(resp.result.length > 0){
              self.lockStatus = resp.result[0].lockStatus;
            }
            if (resp.result.length > 0 && (resp.result[0].status != '2' && resp.result[0].status)) {
              self.startProduce = true;
            }
            self.handleTableData(resp.result);
            self.workList = resp.result;
          }
        });
      },
      handleTableData(result) {
        for (let data of result) {
          for (let attr of this.workLineAttr) {
            if (!data.hasOwnProperty(attr)) {
              data[attr] = "";
            }
          }
          for (let key in data) {
            let value = data[key];
            data[key] = {value: value, edit: false};
          }
        }
      },
    },
    watch: {}
  }
</script>
<style>
  .noEditProduce {
    background: darkgray;
    border: darkgray;
    pointer-events: none;
  }
</style>
